#include "constants.h";

XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power","_vgrp","_wp"];
	DM_Mission_ArtilleryVariables = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};
	
	_convoy_alive = true;
	_convoy_arrived = false;
	_random_end = DM_Chapter_Location;
	_random_end_pos = DM_Chapter_Position;
	_vgrp = DM_GROUP;
	
	_unit_count = count (units _vgrp);
	
	_drivers = [];
	_vehicles = [];
	{
		if (vehicle _x != _x) then {
			_vehicle = vehicle _x;
			_driver = driver _vehicle;
			if (!(_vehicle in _vehicles)) then { _vehicles set [count _vehicles, _vehicle]; };
			if (!(_driver in _drivers)) then { _drivers set [count _drivers, _driver]; };
		};
	} foreach units _vgrp;
	
	{
		_x doMove _random_end_pos;
	} foreach _driver;
	
	[_vehicles, _drivers] spawn {
		private ["_vecs","_units"];
		_vecs = _this select 0;
		_units = _this select 1;
		_alive = true;
		while {_alive AND DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
			_min_speed = 300;
			_alive = false;
			{
				if (alive _x) then {
					// We only consider vehicles which can still move
					if ((speed _x) < _min_speed && canMove _x) then { _min_speed = speed _x; };
				};
			} foreach _vecs;
			if (_min_speed < 30) then { _min_speed = 30; };
			{
				if (alive _x && (alive (driver _x))) then {
					_alive = true;
					_x limitSpeed _min_speed;
				};
			} foreach _vecs;
			{
				if (alive _x) then {
					_alive = true;
					_x limitSpeed _min_speed;
				};
			} foreach _units;
			if (d_mission_debug_messages) then { diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","SpeedLimiter",[_min_speed,_alive,count _vecs, count _units], Time]; };
			sleep 10;
		};
	};
	
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_convoy_alive,_convoy_arrived,_vehicles,_drivers], Time];
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		if (d_mission_debug_messages) then { diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_convoy_alive,_convoy_arrived,_vehicles,_drivers], Time]; };
		
		_vehicle_lost = false;
		_pos_leader = getPos (leader _vgrp);
		{
			if (alive _x && canMove _x && (alive (driver _x)) && (_x distance _pos_leader) > 300) exitWith { _vehicle_lost = true; };
		} foreach _vehicles;
		_vgrp setFormation "FILE";
		_vgrp setSpeedMode "NORMAL";
		_vgrp setBehaviour "CARELESS";
		_vgrp setCombatMode "RED";
		_wp = [_vgrp, currentWaypoint _vgrp];
		if (_vehicle_lost) then {
			if (d_mission_debug_messages) then { diag_log Format["(%1)[%2]: %3: %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","A vehicle is lost", Time]; };
			_wp setWaypointPosition [_pos_leader, 10];
			_wp setWaypointType "MOVE";
			_wp setWaypointSpeed  "NORMAL";
			_wp setWaypointBehaviour "CARELESS";
			_wp setWaypointCombatMode "RED";
			_vgrp setCurrentWaypoint _wp;
		} else {
			_wp setWaypointPosition [_random_end_pos , 50];
			_wp setWaypointType "MOVE";
			_wp setWaypointSpeed  "NORMAL";
			_wp setWaypointBehaviour "CARELESS";
			_wp setWaypointCombatMode "RED";
			_vgrp setCurrentWaypoint _wp;
		};
		_wp_pos = waypointPosition _wp;
		{
			(driver _x) doMove _wp_pos;
		} foreach _vehicles;
		
		_convoy_alive = false;
		_convoy_arrived = true;
		{
			if (vehicle _x != _x) then {
				_vec = vehicle _x;
				// We control there is still an alive vehicle
				if (alive _vec && canMove _vec) then {
					_convoy_alive = true;
					// All alive vehicles must be at target pos
					if ((_vec distance _random_end_pos) > 200) then {
						_convoy_arrived = false;
					};
				};				
			};
		} foreach (units _vgrp);
		
		if (_convoy_alive && _convoy_arrived) then {
			["StopConvoy","", "","",[],"Failed"] call XfMissionTask;
			_chapter_succeeded = false;
			DM_Mission_Chapter_CanRun = false;
		};
		if (!_convoy_alive && !_convoy_arrived) then {
			["StopConvoy","", "","",[],"Succeeded"] call XfMissionTask;
			_chapter_succeeded = true;
			DM_Mission_Chapter_CanRun = false;
		};
	};
	
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};

	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_random_town","_random_town_pos","_random_town_size","_troops_power","_troops_coeff","_grpSoldiers","_grpVehicle","_i","_vgrp","_wp"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];
	
	_map_center = getArray (configFile>>"CfgWorlds">>worldName >> "centerPosition");
	_minimum_dist = (((_map_center select 0) max (_map_center select 1)) * 0.5);
	
	_random_town = [];
	_random_end = [];
	_i_tries = 40;
	_current_dist = 0;
	while { (count _random_town <= 0) && (_i_tries > 0) } do {
		_random_town = [true] call XfMissionGetRandomTown;
		diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Testing Start:",_random_town];
		if (count _random_town > 0) then {
			_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
			_random_town_size = _random_town select XF_MAP_LOCATION_SIZE;
			if ((_random_town_pos distance FLAG_BASE) < 700) then {
				_random_town = [];
			} else {
				_random_end = [];
				_i_tries2 = 20;
				while { (_i_tries2 > 0) } do {
					_random_end_test = [true] call XfMissionGetRandomTown;
					diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Testing End:",_random_end_test];
					if (count _random_end_test > 0) then {
						_random_end_pos = _random_end_test select XF_MAP_LOCATION_CENTER;
						if ((_random_end_pos distance _random_town_pos) > _minimum_dist || (_random_end_pos distance _random_town_pos) > _current_dist) then {
							_current_dist = (_random_end_pos distance _random_town_pos);
							_random_end = _random_end_test;
						};
					};
					_i_tries2 = _i_tries2 - 1;
				};
				if ((count _random_end) <= 0) then { _random_town = []; };
			};
		};
		_i_tries = _i_tries - 1;
	};
	if ((count _random_town) <= 0) exitWith {"Could not pick a random town" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	_random_end_pos = _random_end select XF_MAP_LOCATION_CENTER;
	DM_Chapter_Location = _random_end;
	DM_Chapter_Position = _random_end_pos;
	
	_random_town_name = _random_town select XF_MAP_LOCATION_DISPLAYNAME;
	_random_end_name = _random_end select XF_MAP_LOCATION_DISPLAYNAME;
	diag_log Format["(%1)[%2]: %3: %4 %5 / %6",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Selected Towns:",_random_town, _random_end];
	
	// This indicates where the mission takes place
	[_random_town_pos,_random_town_size,_random_town_name] call XfMissionCurrentPosition;
	
	// Spawn the convoy vehicles.
	// ["T90","T72_RU"],
	// ["BMP3","BRDM2_INS","BMP2_INS","BTR90"],
	// ["BTR90","BRDM2_INS","BRDM2_ATGM_INS"],
	// ["Ural_ZU23_INS","2S6M_Tunguska","Ural_ZU23_INS","ZSU_INS","Ural_ZU23_INS"],
	// ["GAZ_Vodnik","GAZ_Vodnik_HMG","Ural_ZU23_INS"],
	// ["UAZ_MG_INS","UAZ_AGS30_RU","UAZ_MG_INS","UAZ_AGS30_INS","UAZ_MG_INS","UAZ_SPG9_INS","UAZ_MG_INS"],
	// ["KORD","AGS_RU","DSHKM_Ins","2b14_82mm","KORD_high","Metis","DSHkM_Mini_TriPod","SPG9_Ins"],
	// ["ZU23_Ins","Igla_AA_pod_East","ZU23_CDF"],
	// ["D30_RU","GRAD_RU"],
	// ["KamazRefuel"],
	// ["KamazRepair"],
	// ["KamazReammo"]
	_enemy_side_char = switch (d_enemy_side) do {case "EAST": {"E"};case "WEST": {"W"};case "GUER": {"G"};case "CIV": {"G"}; default{"E"};};

	_vehicle_array = missionNamespace getVariable format ["d_veh_a_%1",_enemy_side_char];
	_vec_list = [];
	// One heavy APCs
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_HEAVYAPC) call XfRandomArrayVal)];
	// One light APCs
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_LIGHTAPC) call XfRandomArrayVal)];
	// One Ammo Truck
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_AMMO) call XfRandomArrayVal)];
	// One Light Wheeled
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_LIGHTWHEEL) call XfRandomArrayVal)];
	// Second Ammo Truck
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_AMMO) call XfRandomArrayVal)];
	// One Heavy Wheeled
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_HEAVYWHEEL) call XfRandomArrayVal)];
	
	_vgrp = [_vec_list,false,d_enemy_side,[_random_town_pos,200],[], false, "", "FORM", false] call XfMissionCreateUnitGroup;
	_vgrp setFormation "FILE";
	_vgrp setSpeedMode "NORMAL";
	_vgrp setBehaviour "CARELESS";
	_vgrp setCombatMode "RED";
	for [{_i = (count (waypoints _vgrp));},{_i > 0 ;},{_i = _i - 1}] do {
		deleteWaypoint [_vgrp, _i];
	};
	_wp = _vgrp addWaypoint [_random_end_pos, 200];
	_wp setWaypointType "MOVE";
	_wp setWaypointSpeed  "NORMAL";
	_wp setWaypointBehaviour "CARELESS";
	_vgrp setCurrentWaypoint _wp;
	DM_GROUP = _vgrp;

	[false,["chapter1_start_cross",_random_town_pos, "ICON", "ColorRed", [1,1],"Start",20,"hd_destroy","",0.8]] call XfMissionMarker;
	[false,["chapter1_end_cross",_random_end_pos, "ICON", "ColorRed", [1,1],"End",20,"hd_destroy","",0.8]] call XfMissionMarker;
	
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_random_end_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};
	
	["StopConvoy","Stop the Convoy", Format["A convoy carrying weapons for our enemies is travelling across the country.<br />You need to intercept the convoy before it reaches its destination!<br />It is travelling from %1 to %2.<br />Good luck!", _random_town_name,_random_end_name],"",[],"Created"] call XfMissionTask;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"You tried but failed... you'll do better next time." call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;